//
//  DHSearchCategoryScrollView.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/14.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHSearchCategoryScrollView.h"
#import "DHSearchCategoryItemView.h"
#import "DHCategoryModel.h"

@implementation DHSearchCategoryScrollView

- (NSMutableArray *)categoryArr{
    if (!_categoryArr) {
        _categoryArr = [NSMutableArray array];
    }
    return _categoryArr;
}

- (void)loadCategoryData{
    NSString *sex;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:USER_SELECT_SEX]) {
        sex = [[NSUserDefaults standardUserDefaults] objectForKey:USER_SELECT_SEX];
    }
    if ([GlobalManager shareGlobalManager].user.sex) {
        sex = [GlobalManager shareGlobalManager].user.sex;
    }
    if (!sex) {
        sex = @"男";
    }
    [[DHNetAPIClient shareDHNetAPIClient] request_categoriesWithParams:@{@"sex":sex} andBlock:^(id data, NSError *error) {
        DHCategoryListModel *categoryList = [DHCategoryListModel modelWithDictionary:data];
        [self.categoryArr removeAllObjects];
        [self.categoryArr addObjectsFromArray:categoryList.categories];
        [self upadeCategories];
    }];
}

- (void)upadeCategories{
    [self removeAllSubviews];
    __block CGFloat spaceX = 5;
    __block CGFloat logoW = 50.5;
    __block CGFloat itemLeft = spaceX;
    __weak __typeof(self)weakSelf = self;
    [self.categoryArr enumerateObjectsUsingBlock:^(DHCategoryModel *category, NSUInteger idx, BOOL * _Nonnull stop) {
        CGFloat itemW = logoW + [category.title widthForFont:[UIFont systemFontOfSize:14]];
        DHSearchCategoryItemView *categoryItemView = [[DHSearchCategoryItemView alloc] initWithFrame:CGRectMake(itemLeft, 0, itemW, weakSelf.height) categoryTitle:category.title categoryImgURLString:category.icon];
        [weakSelf addSubview:categoryItemView];
        categoryItemView.tag = idx;
        [categoryItemView addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
        itemLeft += (itemW + spaceX);
    }];
    self.contentSize = CGSizeMake(itemLeft, 0);
}

- (void)clickAction:(UIControl *)sender{
    for (DHSearchCategoryItemView *item in self.subviews) {
        if (item.tag != sender.tag) {
            item.selected = YES;
            [item clickAction:item];
        }
    }
    DHCategoryModel *model = self.categoryArr[sender.tag];
    if (sender.isSelected) {
        [self.delegate searchCategoryScrollViewSelected:model._id];
    }else{
        [self.delegate searchCategoryScrollViewSelected:nil];
    }
}

@end
